/*
 * ShellCommand.cpp
 *
 *  Created on: Apr 27, 2011
 *      Author: user
 */

#include "ShellCommand.h"
#include <stdio.h>
#include <iostream>


ShellCommand::ShellCommand(string& cmd) {
	this->cmd_name = cmd;
	exitStatus = -1;
}

ShellCommand::~ShellCommand() {
}

bool ShellCommand::startExecution() {
	exitStatus = -1;
	if (!(fpipe = (FILE*) popen(cmd_name.c_str(), "r"))) { // If fpipe is NULL
		perror("Pipe does not work. Exiting.");
		exit(1);
	}
	readPipe();
}

string ShellCommand::getOutput() {
	string output(buffer);
	readPipe();
	return output;
}

void ShellCommand::readPipe() {
	if (fgets(buffer, sizeof buffer, fpipe)) {
		hasOutput = true;
		exitStatus = -1;
	} else {
		exitStatus = pclose(fpipe);
		hasOutput = false;
	}
}

void printOutput(ShellCommand& cmd) {
	while (cmd.hasOutput) {
		cout << cmd.getOutput();
	}
}

void printCmd(ShellCommand& cmd) {
	cout << cmd.cmd_name << endl;
}
void printResult(ShellCommand& cmd) {
	if (cmd.exitStatus == 0) {
		cout << "DONE: " <<  cmd.cmd_name.substr(0,cmd.cmd_name.find_first_of(string(" "),0)) << endl << endl;
	} else {
		cout << "ERROR: " << cmd.cmd_name.substr(0,cmd.cmd_name.find_first_of(string(" "),0)) << endl << endl;
	}

}

ShellCommand exec(string & str)
{
    ShellCommand cmd(str);
    printCmd(cmd);
    cmd.startExecution();
    printOutput(cmd);
    printResult(cmd);
    return cmd;
}
